import axios from 'axios'
import { message } from 'ant-design-vue'
import { useAccountStore } from '@/stores/account'

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL + import.meta.env.VITE_APP_BASE_API,
  responseType: 'json',
  validateStatus(status) {
    return status === 200
  }
})
// Request interceptors
/**
 * @param NoPostSeqNo 参数是否带公共参数 seqNo,在api方法传递参数，exam:account.js fetchSeqNo()
 * @param {skipErrorHandler} boolean 是否跳过同一封装的报错处理
 */
let skipErrorHandler = false
service.interceptors.request.use(
  (config) => {
    const { method } = config
    const accountStore = useAccountStore()
    const seqNo = accountStore.seqNo
    skipErrorHandler = !!config?.otherConfigs?.skipErrorHandler
    if (method === 'post') {
      if (!config?.otherConfigs?.NoPostSeqNo) {
        config.data = { ...config.data, seqNo }
      }
    }
    return config
  },
  (error) => {
    Promise.reject(error)
  }
)

// Response interceptors
service.interceptors.response.use(
  async (response) => {
    const { data, status } = response
    const { success } = data || {}
    if (status == 200 && success == '0') {
      return response.data
    } else {
      if (skipErrorHandler) {
        return
      }
      message.error(response.data.errorMsg || '未知错误')
      return Promise.reject(response.data)
    }
  },
  (error) => {
    message.error(error.message || '服务器报错')
    return Promise.reject(error)
  }
)

export default service
